#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
#include "timer.h"

struct _timer_info {
		int state;	/* on or off */
		struct timespec interval;
		struct timespec start;
} timer_info[MAX_TIMER_CNT];

struct timespec delta_time(struct timespec start,struct  timespec end)
{
     struct timespec temp;
     if ((end.tv_nsec-start.tv_nsec)<0) {
         temp.tv_sec = end.tv_sec-start.tv_sec-1;
         temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
     } else {
         temp.tv_sec = end.tv_sec-start.tv_sec;
         temp.tv_nsec = end.tv_nsec-start.tv_nsec;
     }
     return temp;
}

int timeout(rt_timer_t t)
{
	struct timespec now,d;	
	int timeout=0;
	clock_gettime(CLOCK_REALTIME, &now);
	d=delta_time(timer_info[t].start,now);	
	
	if(d.tv_sec>timer_info[t].interval.tv_sec)
		timeout=1;
	else if((d.tv_sec==timer_info[t].interval.tv_sec)&&(d.tv_nsec>=timer_info[t].interval.tv_nsec))
		timeout=1;
	//printf("timeout:%d\ndifference:%d sec,%ld nsec\n",timeout,d.tv_sec,d.tv_nsec );
	return timeout;
}

void init_timer(rt_timer_t t,int rate)
{
		timer_info[t].state = 0;	//off
		switch (t) {
		case RG_REQ:
			timer_info[t].interval.tv_sec= TIMEOUT_RG_REQ;
			timer_info[t].interval.tv_nsec= TIMEOUT_RG_REQ_N;
			break;
		case RG_RESP:
			timer_info[t].interval.tv_sec = TIMEOUT_RG_RESP;
			timer_info[t].interval.tv_nsec = TIMEOUT_RG_RESP_N;
			break;
		case SEND:
			timer_info[t].interval.tv_sec = 0;
			timer_info[t].interval.tv_nsec = (10000000L)/(rate/100);
			break;
		case SEND_WINDOW:
			timer_info[t].interval.tv_sec =  TIMEOUT_SEND_WINDOW;
			timer_info[t].interval.tv_nsec =  TIMEOUT_SEND_WINDOW_N;
			break;
		case RECV_WINDOW:
			timer_info[t].interval.tv_sec =  TIMEOUT_RECV_WINDOW;
			timer_info[t].interval.tv_nsec =  TIMEOUT_RECV_WINDOW_N;
			break;
		}
	printf("interval:%d sec,%ld nsec\n",timer_info[t].interval.tv_sec,timer_info[t].interval.tv_nsec );
}


void reset_timer(rt_timer_t t)
{
	timer_info[t].state = 1;	//on
	clock_gettime(CLOCK_REALTIME, &(timer_info[t].start));
}



